package com.fengyunhe.manager.service.impl;


import com.fengyunhe.common.bean.PageList;
import com.fengyunhe.manager.CurrentUser;
import com.fengyunhe.manager.dao.AdminRoleDao;
import com.fengyunhe.manager.dao.AdminUserRoleBindDao;
import com.fengyunhe.manager.dao.entity.AdminRoleEntity;
import com.fengyunhe.manager.dao.entity.AdminRolePermBindEntity;
import com.fengyunhe.manager.service.AdminRoleService;
import com.fengyunhe.common.bean.Page;
import com.fengyunhe.manager.dao.AdminRolePermBindDao;
import com.fengyunhe.manager.vo.RoleVo;
import org.apache.shiro.cache.CacheManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 角色service
 */
@Service
public class AdminRoleServiceImpl implements AdminRoleService {

    @Resource
    private AdminRoleDao adminRoleDao;
    @Resource
    private AdminUserRoleBindDao adminUserRoleBindDao;
    @Resource
    private AdminRolePermBindDao adminRolePermBindDao;

    @Resource
    CacheManager shiroCacheManager;


    @Override
    public Integer createRole(RoleVo sysRole, String... permString) {
        AdminRoleEntity role = new AdminRoleEntity();
        role.setCreatedAt(new Timestamp(System.currentTimeMillis()));

        role.setDescription(sysRole.getDescription());
        role.setRoleName(sysRole.getRoleName());
        role.setCreatedByUserId(CurrentUser.get().getUserId());
        role.setCreatedByRealName(CurrentUser.get().getRealName());

        adminRoleDao.save(role);

        if (permString != null) {
            for (int i = 0; i < permString.length; i++) {
                AdminRolePermBindEntity e = new AdminRolePermBindEntity();
                e.setPerm(permString[i]);
                e.setAdminRoleByRoleId(role);
                adminRolePermBindDao.save(e);
            }
        }
        this.adminRoleDao.flush();
        return role.getRoleId();
    }


    @Override
    public PageList<RoleVo> getRolePageList(Page page) {
        StringBuilder hql = new StringBuilder();
        hql.append("select new ");
        hql.append(RoleVo.class.getName());
        hql.append(" ( ");
        hql.append(" s.roleId,s.roleName,s.description,s.createdAt,s.createdByUserId,s.createdByRealName ");
        hql.append(" ) ");
        hql.append(" from AdminRoleEntity as s order by s.createdAt desc");
        return adminRoleDao.findPageList(page, RoleVo.class, hql.toString());
    }


    @Override
    public boolean updateRole(RoleVo role, String... permString) {
        this.adminRolePermBindDao.deleteResultsByProperty("adminRoleByRoleId.roleId", role.getRoleId());
        this.adminRoleDao.flush();
        AdminRoleEntity old = this.adminRoleDao.getById(role.getRoleId());
        old.setDescription(role.getDescription());
        old.setRoleName(role.getRoleName());
        this.adminRoleDao.update(old);
        if (permString != null) {
            for (int i = 0; i < permString.length; i++) {
                AdminRolePermBindEntity e = new AdminRolePermBindEntity();
                e.setPerm(permString[i]);
                e.setAdminRoleByRoleId(old);
                adminRolePermBindDao.save(e);
            }
        }
        this.adminRoleDao.flush();
        shiroCacheManager.getCache("authorizationCache").clear();
        return true;
    }


    @Override
    public boolean deleteRole(Integer roleId) {
        //删除角色上的权限
        this.adminRolePermBindDao.deleteResultsByProperty("adminRoleByRoleId.roleId", roleId);
        //删除与用户的关系
        this.adminUserRoleBindDao.deleteResultsByProperty("adminRoleByRoleId.roleId", roleId);
        //删除角色
        adminRoleDao.deleteById(roleId);
        shiroCacheManager.getCache("authorizationCache").clear();

        return true;
    }

    @Override
    public Set<String> getPermissionsByRoleId(Integer roleId) {
        List<AdminRolePermBindEntity> rolePermRelation = this.adminRolePermBindDao.findListByProperty("adminRoleByRoleId.roleId", roleId);
        if (rolePermRelation == null) {
            return null;
        }
        Set<String> perms = new HashSet<String>();
        for (AdminRolePermBindEntity sysRolePerm : rolePermRelation) {
            perms.add(sysRolePerm.getPerm());
        }
        return perms;
    }


    @Override
    public List<RoleVo> getAllRoleList() {
        StringBuilder hql = new StringBuilder();
        hql.append("select new ");
        hql.append(RoleVo.class.getName());
        hql.append(" ( ");
        hql.append(" s.roleId,s.roleName,s.description,s.createdAt,s.createdByUserId,s.createdByRealName ");
        hql.append(" ) ");
        hql.append(" from AdminRoleEntity as s order by s.createdAt desc");
        return adminRoleDao.findList(RoleVo.class, hql.toString());
    }

    @Override
    public List<Integer> getRoleIdListByAdminUserId(Integer userId) {
        String hql = "select adminRoleByRoleId.roleId from AdminUserRoleBindEntity where adminUserByUserId.userId = ?";
        List<Integer> roleIdList = this.adminRoleDao.findList(Integer.class, hql, userId);
        return roleIdList;
    }
}
